/**
 * $Id$
 *
 * Copyright (c) 2014 ChinaSoft International, Ltd. All rights reserved
 * JointForce Project
 *
 */
package com.csi.jf.crucible.api.crucible;

import java.io.IOException;
import java.util.Iterator;

import com.chinasofti.ro.bizframework.modules.json.JSONArray;
import com.chinasofti.ro.bizframework.modules.json.JSONObject;
import com.icss.j2ee.util.http.HttpClientException;

/**
 * @Title: ApiTestRepository.java
 * @Description: <br>
 *               <br>
 * @Company: Chinasofti
 * @Created on 2014-7-4 下午3:24:33
 * @author zhangmh
 * @version $Revision: 1.0 $
 * @since 1.0
 */
public class ApiTestRepository {

    private RestClient client = new RestClient();
    
    public static void main(String[] args) throws Exception{
        ApiTestRepository test = new ApiTestRepository();
        String repoName = "Portal_rp";
//        test.addRepository();
        test.deleteRepositoryByName(repoName);
//        test.testListRepositoriesContent();
//        test.listRepositories();
//        System.out.println(test.isExistRepository(repoName));
    }
    
    public void startRepo() throws HttpClientException, IOException{
        String url = "/rest-service-fecru/admin/repositories/CrucibleTest/start";
        client.doGet(url);
    }
    
    public void stopRepo() throws HttpClientException, IOException{
        String url = "/rest-service-fecru/admin/repositories/CrucibleTest/stop";
        client.doGet(url);
    }
    
    /**
     * @param type - SUBVERSION, PERFORCE, GIT, HG, CVS
       @param name - repository name
       @param url - svn url, perforce host, git/hg location, cvs dir
       @param path - svn/perforce/git/hg path [optional]
       @param description - repository description [optional]
       @param username - svn/perforce username [optional]
       @param password - svn/perforce/git/hg password [optional]
       @return
       
     * @throws Exception
     */
    public void addRepository()throws Exception{
        //Adds repository
        String url = "/rest-service-fecru/admin/repositories-v1?type=GIT&name=JFPts&url=https://zhangmh%40chinasofti.com@git.jointforce.com/scm/join/jfpts.git&username=zhangmh&password=zhangmh2013";
        url = "/plugins/servlet/git-repo-api/update?url=https://zhangmh%40chinasofti.com@git.jointforce.com/scm/join/jftestrepo.git&name=jftestrepo";
        client.doGet(url);
    }
    
    /**
     * list all repositories
     * @throws HttpClientException
     * @throws IOException
     * @Created on 2014-7-8 下午9:55:43
     * @author FengHaiBing
     */
    public void listRepositories() throws HttpClientException, IOException {
        String url = "/rest-service-fecru/admin/repositories-v1?type=GIT&name=JFPts&url=https://zhangmh%40chinasofti.com@git.jointforce.com/scm/join/jfpts.git&username=zhangmh&password=zhangmh2013";
        url = "/rest-service/repositories-v1";
    }
    
    /**
     * {
  "path" : "trunk",
  "dir" : [ {
    "path" : "trunk/src",
    "link" : {
      "href" : "http://localhost:8060/crucible/rest-service/repositories-v1/browse/REPO/trunk/src",
      "rel" : "self"
    }
  }, {
    "path" : "trunk/test",
    "link" : {
      "href" : "http://localhost:8060/crucible/rest-service/repositories-v1/browse/REPO/trunk/test",
      "rel" : "self"
    }
  } ],
  "file" : [ {
    "path" : "trunk/pom.xml",
    "revision" : "1234",
    "details" : {
    },
    "diffRevision" : {
    },
    "link" : {
      "href" : "http://localhost:8060/crucible/rest-service/repositories-v1/content/REPO/1234/trunk/pom.xml",
      "rel" : "content"
    }
  } ]
}
     * 
     * @param repoName
     * @param json
     * @throws HttpClientException
     * @throws IOException
     * @Created on 2014-7-11 下午6:26:13
     * @author FengHaiBing
     */
    public void listRepositoriesContent(String repoName, String json) throws HttpClientException, IOException {
//        String url = "/rest-service/repositories-v1/browse/{repo}/{path:.*$}";

    		
        String url = "/rest-service/repositories-v1/browse/"+repoName+"/resources:*.properties$";
        String restReturn = client.doGet(url);
    	
    }
    
    public void testListRepositoriesContent() throws HttpClientException, IOException {
    	String repoName = "jftestrepo";
    	StringBuffer sbJson = new StringBuffer();
    	sbJson
    	.append("{")
    		.append("  \"path\" : \"develop\",")
    		.append("  \"dir\" : [ {")
    		.append("    \"path\" : \"develop/sample\",")
    		.append("    \"link\" : {")
    		.append("      \"href\" : \"http://115.29.76.124:8060/crucible/rest-service/repositories-v1/browse/"+repoName+"/\",")
//    		.append("      \"href\" : \"http://115.29.76.124:8060/browse/~br=develop/"+repoName+"/\",")
    		.append("      \"rel\" : \"self\"")  
    		.append("    }")
    		.append("  } ]")
    		.append("}");
    	
    	listRepositoriesContent(repoName, sbJson.toString());
    }
    
    /**
     * whether the repository with the name repoName was created
     * @param repoName
     * @return
     * @Created on 2014-7-8 下午10:02:11
     * @author FengHaiBing
     * @throws IOException 
     * @throws HttpClientException 
     */
    public boolean isExistRepository(String repoName) throws HttpClientException, IOException {
    	if(repoName == null) return false;
        String url = "//rest-service/repositories-v1";
        String restReturn = client.doGet(url);
    	if(restReturn == null) return false;
    	
    	JSONObject jo = JSONObject.fromObject(restReturn);
    	if(jo == null || jo.get("repoData") == null) return false;
    	
    	JSONArray ja = (JSONArray)jo.get("repoData");
    	
    	Iterator<JSONObject> it = ja.iterator();
    	while (it.hasNext()) {
    		JSONObject ne = it.next();
    		String pn = (ne.get("name") == null ? "" : ne.get("name").toString() );
    		if(repoName.equalsIgnoreCase(pn)) return true;
    	}
    	return false;
    }
    
    public void deleteRepository()throws Exception{
        //delete a repository
        String url = "/plugins/servlet/git-repo-api/delete?name=jftestrepo";
        client.doGet(url);
    }
    
    public void deleteRepositoryByName(String repoName)throws Exception{
        //delete a repository
        String url = "/plugins/servlet/git-repo-api/delete?name=" + repoName;
        client.doGet(url);
    }
    
    /**
     * 创建 repository
     * 
     * @param creator
     * @param repoName
     * @throws Exception
     * @Created on 2014-7-8 下午4:03:00
     * @author FengHaiBing
     * @throws IOException 
     * @throws HttpClientException 
     */
    public void createRepository(String creator, String repoName) throws HttpClientException, IOException {
    	if(isExistRepository(repoName)) return ;
        String url = "/plugins/servlet/git-repo-api/update?url=https://"+creator+"@git.jointforce.com/scm/join/" + repoName + ".git&name=" + repoName;
        client.doGet(url);
    }
    
    /**
     * @param {repo} string repository-name
     * @return
     *{
        "name": "CrucibleTest", 
        "state": "RUNNING", 
        "enabled": true, 
        "indexingStatus": {
            "linesOfContentIndexingInProgress": false, 
            "crossRepositoryRescanInProgress": false, 
            "error": false, 
            "fullIndexingInProgress": false, 
            "initialScanningComplete": true, 
            "lastScanTime": 1403839447809, 
            "incrementalIndexingInProgress": false, 
            "fullRepositorySlurpDone": true, 
            "indexingStateCounts": {
                "INFILLED": 0, 
                "COMPLETE": 0, 
                "METADATA_INDEXED": 0, 
                "SCANNED": 0, 
                "CONTENT_INDEXED": 0, 
                "UNKNOWN": 3
            }
        }
     }
     */
    public void getRepositoryStatus()throws Exception{
        String url = "/rest-service-fecru/admin/repositories-v1/CrucibleTest";
        client.doGet(url);
    }
    
}
